using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BulletOnRails4NET.Controllers;
using GeneCMS.Models.physical;
using Suteki.Common.Repositories;
using GeneCMS.Models.logical;
using BulletOnRailsNET.Models.FormBuilder;
using GeneCMS.Models.View;
using LivePhotoDataProvider;

namespace GeneCMS.Controllers
{
    [Authorize]
    public class ContentsController : GenePublicController //ScaffoldController<Content>
    {

        #region CRUD_METHODS
        [AcceptVerbs("GET")]
        public ActionResult List(int id)
        {
            return CreateCrudViewResult(null, "", id);
        }

        private ViewResult CreateCrudViewResult(ContentView curr_product, string message, int pageid)
        {
            if (curr_product == null)
                curr_product = new ContentView();
            CrudFormViewModel<ContentView> model = new CrudFormViewModel<ContentView>();
            var db = new CMSDBDataContext();
            model.List = db.GetContentsForPage(pageid, User.Identity.Name).Select(m => new ContentView(m)).ToList();
            //model.List = db.GetAll().Where(a => a.PageID == pageid).Select(m => new ContentView(m));
            model.CurrentModel = curr_product;
            model.MetadataType = null;
            model.PropertiesToCrud = typeof(ContentView).GetProperties();
            model.StatusMessage = EscapeJS(message);
            model.ParentID = pageid;
            return View("CRUDForm", model);
        }

        [AcceptVerbs("POST")]
        [ValidateInput(false)]
        public ActionResult Edit(int id, ContentView content)
        {

            var db = new Repository<Content>();
            var prodcut = db.GetById(content.ID);
            try
            {
                var sp_executor = new CMSDBDataContext();
                sp_executor.ContentUpdate(content.ID, content.Title, content.Html, content.ElementMatchCriteria,
                    content.PageID, content.AttributeToMatch, User.Identity.Name);
                //UpdateModel<Content>(prodcut);
                //db.SubmitChanges();
                return CreateCrudViewResult(content, "Object Saved", id);
            }
            catch (Exception e)
            {

                return CreateCrudViewResult(content, "Error Updating object: " + e.ToString(), id);
            }
        }

        [AcceptVerbs("POST")]
        [ValidateInput(false)]
        public ActionResult Create(int id, ContentView content)
        {
            var db = new Repository<Content>();
            try
            {

                var sp_executor = new CMSDBDataContext();
                sp_executor.ContentInsert(content.Title, content.Html, content.ElementMatchCriteria,
                    content.PageID, content.AttributeToMatch, User.Identity.Name);
                //var new_db_content = new Content();
                //content.ExportValuesToContent(new_db_content);
                //db.InsertOnSubmit(new_db_content);
                //db.SubmitChanges();
                return CreateCrudViewResult(content, "Object Created", id);
            }
            catch (Exception e)
            {
                return CreateCrudViewResult(content, "Error Creating object: " + e.ToString(), id);
            }
        }
        [AcceptVerbs("POST")]
        public ActionResult Delete(int id, int DeleteID)
        {
            var db = new Repository<Content>();
            var prodcut = db.GetById(DeleteID);
            try
            {
                if (prodcut == null)
                {
                    return CreateCrudViewResult(null, "Error Deleting object: Object not found with ID " + DeleteID, id);

                }
                else
                {
                    var sp_executor = new CMSDBDataContext();
                    sp_executor.ContentDelete(DeleteID, User.Identity.Name);
                    //db.DeleteOnSubmit(prodcut);
                    //db.SubmitChanges();
                    return CreateCrudViewResult(null, "Object Created", id);
                }
            }
            catch (Exception e)
            {
                return CreateCrudViewResult(null, "Error Deleting object: " + e.ToString(), id);
            }
        }
        #endregion


        [AcceptVerbs("GET")]
        public ActionResult ImgSelection()
        {
            return View();
        }
        [AcceptVerbs("POST")]
        public ActionResult ImgSelection(string live_rss_url)
        {
            LivePhotoData app = new LivePhotoData();
            var albums = app.GetAlbums(live_rss_url,true); //"http://picturethat.spaces.live.com/feed.rss", true);
            return PartialView("LivePhotoSelector",albums);
        }
        //[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        //public override ActionResult Create(FormCollection formValues)
        //{
        //    return base.Create(formValues);
        //}

        //[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
        //public override JsonResult Edit(int id, FormCollection formValues)
        //{
        //    return base.Edit(id, formValues);
        //}

         //[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
         //public override ActionResult EditMultiple(FormCollection formValues)
         //{
         //    return base.EditMultiple(formValues);
         //}

        /// <summary>
        /// Gets all the content elements from a specified page.
        /// </summary>
        /// <param name="id">Id of the page that contains the contents</param>
        /// <returns>All the contents converted to JSon friendly objects</returns>
         public ActionResult ContentsForPage(int id)
         {
             Repository<Content> data = new Repository<Content>();
             var json_contents = from data_rows in data.GetAll()
                                 where data_rows.PageID == id
                                 select new ContentEdit(data_rows);
             return Json( json_contents, JsonRequestBehavior.AllowGet );
         }
    }
}
